package com.coincalf.wallet.blockchain.client;

import com.coincalf.feign.CoinServiceClient;
import com.coincalf.framework.enums.TxStateEnum;
import com.coincalf.wallet.blockchain.BlockConstant;
import com.coincalf.wallet.blockchain.bean.TransInfo;
import com.coincalf.wallet.blockchain.util.AESUtil;
import io.eblock.eos4j.EosRpc;
import io.eblock.eos4j.api.vo.transaction.Transaction;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Slf4j
@Component
public class EosClientSingle {

    @Autowired
    private CoinServiceClient coinServiceClient;

    private static CoinServiceClient coinClient;

    @PostConstruct
    public void init() {
        EosClientSingle.coinClient = coinServiceClient;
    }

    private EosClientSingle() {
    }

    private static volatile EosRpc eosClient = null;

    public static EosRpc getEosClient() {
        //获取Eos单例客户端
        if (eosClient == null) {
            synchronized (EosClientSingle.class) {
                if (eosClient == null) {
                    try {
                        eosClient = new EosRpc(coinClient.selectRpcServerUrl("EOS"));
                    } catch (Exception e) {
                        log.warn("获取EOS CLIENT ERROR e={}", e);
                        e.printStackTrace();
                    }
                }
            }
        }
        return eosClient;
    }

    public static TransInfo trans(TransInfo transInfo) {
        String decrypt = AESUtil.decrypt(transInfo.getPrivateKey(), BlockConstant.AES_KEY);
        Transaction transfer = EosClientSingle.getEosClient().transfer(
                decrypt,
                transInfo.getFromAddress(),
                transInfo.getToAddress(),
                transInfo.getAmount() + " EOS",
                "eosio.token",
                ""
        );
        transInfo.setTxHash(transfer.getTransactionId());
        transInfo.setStatus(TxStateEnum.TO_BE_CONFIRMED.getStatus());
        return transInfo;
    }

}
